﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public static class StringExtend
{
    /// <summary>
    /// 确定此字符串实例的结尾是否与指定的字符串匹配。<br/>
    /// 比原生 String.EndsWith 效率高
    /// </summary>
    public static bool EndsWith_Custom(this string a, string b)
    {
        int ap = a.Length - 1;
        int bp = b.Length - 1;

        while (ap >= 0 && bp >= 0 && a[ap] == b[bp])
        {
            ap--;
            bp--;
        }
        return (bp < 0);
    }

    /// <summary>
    /// 确定此字符串实例的开头是否与指定的字符串匹配。<br/>
    /// 比原生 String.StartsWith 效率高
    /// </summary>
    public static bool StartsWith_Custom(this string a, string b)
    {
        int aLen = a.Length;
        int bLen = b.Length;

        int ap = 0; int bp = 0;

        while (ap < aLen && bp < bLen && a[ap] == b[bp])
        {
            ap++;
            bp++;
        }

        return (bp == bLen);
    }

    /// <summary>
    /// 相当于 Equals(b, StringComparison.Ordinal);<br/>
    /// 效率比 Equals(b) 高
    /// </summary>
    /// <param name="ignoreCase">是否忽略大小写</param>
    public static bool EqualsOrdinal(this string a,string b,bool ignoreCase = false)
    {
        return a.Equals(b, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
    }

    /// <summary>
    /// 找出两个字符串相同的字串
    /// </summary>
    public static List<string> GetIntersection(this string str1, string str2)
    {
        string str = "";
        List<string> list = new List<string>();
        int i1 = str1.Length;
        for (int i = 1; i < i1; i++)
        {
            //最后的剩余长度没匹配出的长，跳出循环
            if (i1 - i - 1 < str.Length) break;
            //判断前面提取跟匹配到的长度一样长的字符是否匹配。不匹配跳出这次
            //这四句才是提升性能的主干
            int cishu = 2;
            if (str.Length != 0) { cishu = str.Length; }
            if (i + cishu > i1) return null;//匹配到最后都没有 就返回null
            if (!str2.Contains(str1.Substring(i, cishu))) continue;

            for (int j = i1 - i; j > 0; j--)
            {
                string temp = str1.Substring(i, j);
                if (str2.Contains(temp))
                {
                    if (temp.Length > str.Length)
                    {
                        list.Clear();
                        str = temp;
                        list.Add(str);
                        break;//每一次匹配找出第一个，肯定是这组里最长的，因为是从后面匹配的。直接跳出这次
                    }
                    else if (temp.Length == str.Length)
                    {
                        list.Add(temp);
                    }
                }
            }
        }
        return list;
    }
}
